package com.mingqijia.gassafety.authority.security.facade;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mingqijia.gassafety.authority.api.req.resource.*;
import com.mingqijia.gassafety.authority.api.resp.resource.OperationRespDTO;
import com.mingqijia.gassafety.authority.api.resp.resource.ResourceLiteRespDTO;
import com.mingqijia.gassafety.authority.api.resp.resource.ResourceRespDTO;
import com.mingqijia.gassafety.authority.api.web.facade.ResourceManageFacade;
import com.mingqijia.gassafety.authority.dal.command.CreateResourceCommand;
import com.mingqijia.gassafety.authority.dal.command.RemoveResourceCommand;
import com.mingqijia.gassafety.authority.dal.command.UpdateResourceCommand;
import com.mingqijia.gassafety.authority.dal.handler.ConfigureTranslator;
import com.mingqijia.gassafety.authority.dal.handler.ResourceTranslator;
import com.mingqijia.gassafety.authority.dal.provider.ManagerProvider;
import com.mingqijia.gassafety.authority.dal.provider.ResourceProvider;
import com.mingqijia.gassafety.db.entity.auth.ManagerEntry;
import com.mingqijia.gassafety.db.entity.auth.ResourceEntry;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.enums.ResourceType;
import com.mingqijia.gassafety.shared.enums.RunningState;
import com.mingqijia.gassafety.shared.facade.BaseFacade;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.shared.utils.MappingTools;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * REST接口
 * @author Damon S.
 * @version v0.2
 * @date 2021-06-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class ResourceManageFacadeImpl extends BaseFacade implements ResourceManageFacade {

    private final ConfigureTranslator translator2;
    private final ResourceProvider provider;
    private final ResourceTranslator translator;
    private final ManagerProvider mProvider;


    @Override
    public PageUtil<ResourceRespDTO> findResource(QueryResourceReqDTO req) {
        Page<ResourceEntry> results = provider.find(translator.toCommand(req));
        return PageUtil.init(results, translator.toRespDTO(results.getRecords()));
    }

    @Override
    public List<ResourceLiteRespDTO> buildHierarchy() {
        String userId = getUserBackendId();
        // 平台管理员可以看到所有资源
        if (Objects.equals(Constants.PLATFORM_SA, userId)) {
            return provider.buildResourceHierarchy();
        }
        // 启用用户可以看到自己的资源
        ManagerEntry entry = mProvider.getById(userId);
        if (ObjectUtils.isEmpty(entry)) {
            throw new GlobalAuthenticationException("用户不存在");
        }
        return provider.buildResourceHierarchy(
                MappingTools.fromRaw(entry.getRoleId())
        );
    }

    @Override
    public String createResource(CreateMenuResourceReqDTO req) {
        CreateResourceCommand command = translator.toCommand(req);
        command.setType(ResourceType.MENU);
        return provider.create(command);
    }

    @Override
    public String createResource(CreateFuncResourceReqDTO req) {
        CreateResourceCommand command = translator.toCommand(req);
        command.setType(ResourceType.FUNC);
        return provider.create(command);
    }

    @Override
    public void updateResource(UpdateMenuResourceReqDTO req) {
        UpdateResourceCommand command = translator.toCommand(req);
        command.setType(ResourceType.MENU);
        if (!provider.update(command)) {
            throw new GlobalAuthenticationException("操作失败");
        }
    }

    @Override
    public void updateResource(UpdateFuncResourceReqDTO req) {
        UpdateResourceCommand command = translator.toCommand(req);
        command.setType(ResourceType.FUNC);
        if (!provider.update(command)) {
            throw new GlobalAuthenticationException("操作失败");
        }
    }

    @Override
    public void removeResource(String[] resId) {
        RemoveResourceCommand command = RemoveResourceCommand.builder()
                .resIds(Arrays.asList(resId)).build();
        if (!provider.remove(command)) {
            throw new GlobalAuthenticationException("删除资源失败");
        }
    }

    @Override
    public void switchResource(String resId, Integer state) {
        if (state > Constants.INT_ONE || state < Constants.INT_ZERO) {
            throw new GlobalAuthenticationException("请求参数不合法");
        }
        UpdateResourceCommand command = UpdateResourceCommand.builder()
                .resId(resId).state(RunningState.parse(state)).build();
        provider.update(command);
    }

    @Override
    public List<OperationRespDTO> getFunctions() {
        return translator2.toOpRespDTO(provider.findRawOperations());
    }
}
